package com.walnut.lom_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.walnut.lom_system.common.enums.OrderEnum;
import com.walnut.lom_system.common.lang.Const;
import com.walnut.lom_system.common.util.CopyUtil;
import com.walnut.lom_system.common.util.EntityUtil;
import com.walnut.lom_system.common.util.ExcelImportUtil;
import com.walnut.lom_system.domain.dto.ExcelUserInfoDto;
import com.walnut.lom_system.domain.entity.EmployInfo;
import com.walnut.lom_system.domain.entity.UserInfo;
import com.walnut.lom_system.domain.entity.UserLoginInfo;
import com.walnut.lom_system.domain.form.UserInfoForm;
import com.walnut.lom_system.domain.form.UserInfoSearchForm;
import com.walnut.lom_system.domain.vo.EmployInfoVo;
import com.walnut.lom_system.domain.vo.UserInfoVo;
import com.walnut.lom_system.mapper.*;
import com.walnut.lom_system.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenhetao
 * @description 针对表【user_info(记录每个用户的用户信息)】的数据库操作Service实现
 * @createDate 2022-03-08 18:07:10
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserLoginInfoMapper userLoginInfoMapper;

    @Autowired
    private RoleInfoMapper roleInfoMapper;

    @Autowired
    private DepartmentInfoMapper departmentInfoMapper;

    @Autowired
    private RoleDepartmentMapper roleDepartmentMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public boolean importUserInfo(MultipartFile multipartFile) {
        List<ExcelUserInfoDto> excelUserInfoDtos = new ExcelImportUtil().importUserInfo(multipartFile);
        if (excelUserInfoDtos == null) {
            //转换失败
            log.warn("转换失败");
            return false;
        }
        //用户信息写入
        List<UserInfo> userInfos = CopyUtil.copyListUserFromExcel(excelUserInfoDtos);

        //TODO delete
        Map<String, Object> columnMap = new HashMap<String, Object>();
        columnMap.put("academy", "计算机科学学院");
        userInfoMapper.deleteByMap(columnMap);
        int i = userInfoMapper.insertBatch(userInfos);


        //登录信息及角色部门信息写入写入
        for (ExcelUserInfoDto excelUserInfoDto : excelUserInfoDtos) {
            UserLoginInfo userLoginInfo = new UserLoginInfo();
            userLoginInfo.setSid(excelUserInfoDto.getUserSid());
            userLoginInfo.setEmail(excelUserInfoDto.getEmail());
            //写入登录信息
            userLoginInfoMapper.insert(userLoginInfo);
//
//            //TODO 角色及部门信息写入
//            String department = excelUserInfoDto.getDepartment();
//            String position = excelUserInfoDto.getPosition();
//
//            //部门不存在
//            if (departmentInfoMapper.selectByMap(Map.of("department_name",department)).isEmpty()){
//                //创建部门
//
//            }
//
//            //角色不存在
//            if (roleDepartmentMapper.selectByMap(Map.of("name",position)).isEmpty()){
//                //创建角色
//
//            }
//            //关系写入
//
        }

        return true;
    }

    @Override
    public UserInfoVo getUser(UserInfoForm userInfoForm) {
        //将UserInfoForm 转化为 UserInfo
        UserInfo userInfoIn = CopyUtil.copy(userInfoForm, UserInfo.class);
        System.out.println(userInfoIn);
        //查询用户
        QueryWrapper<UserInfo> userQueryWrapper = Wrappers.query(userInfoIn);
        UserInfo userInfoOut = userInfoMapper.selectOne(userQueryWrapper);
        //将查询用户转化为UserInfoVo并返回
        return CopyUtil.copy(userInfoOut, UserInfoVo.class);
    }

    //TODO Test
    @Override
    public UserInfoVo getUserById(long id) {
        return CopyUtil.copy(userInfoMapper.selectById(id), UserInfoVo.class);
    }

    @Override
    public Page<UserInfoVo> getList(UserInfoSearchForm userInfoSearchForm) {
        UserInfo userInfo = CopyUtil.copy(userInfoSearchForm, UserInfo.class);
        String orderName = null;
        if (userInfoSearchForm.getOrderBy() != null) {
            try {
                orderName = OrderEnum.valueOfName(userInfoSearchForm.getOrderBy()).getOrderName();
            } catch (NullPointerException e) {
                log.error("输入排序有误，采用默认排序");
            }
        }
        log.info(String.valueOf(userInfoSearchForm.getAsc()));
        Page<UserInfo> result = userInfoMapper.queryConditionList(
                new Page<>(userInfoSearchForm.getPageNum(), userInfoSearchForm.getPageSize()),
                userInfo,
                orderName,
                userInfoSearchForm.getAsc()
        );

        return CopyUtil.dto2Vo(result, UserInfoVo.class);
    }

    @Override
    public int deleteUser(long id) {
//        return userInfoMapper.deleteById(id)==1? Const.OP_SUCCESS:Const.OP_NO_EFFECT;
        //效果同上，不过上面那个可读性可能会好一点
        return userInfoMapper.deleteById(id);
    }

    @Override
    public int updateUser(long id, UserInfoForm userInfoForm) {

        //控制无法修改id
        userInfoForm.setId(null);

        UserInfo copy = CopyUtil.copy(userInfoForm, UserInfo.class, UserInfoForm.class);

        UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq("id", id);

        int i = userInfoMapper.update(copy, updateWrapper);

        if (i == 1) {
            return Const.OP_SUCCESS;
        } else {
            return Const.OP_NO_EFFECT;
        }
    }
}





